package com.jeecg.demo.controller;

import com.alibaba.fastjson.JSONArray;
import com.jeecg.demo.entity.*;
import com.jeecg.demo.service.*;
import com.jeecg.demo.util.GetUserTenantId;
import com.jeecg.demo.util.PopupDataBindUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.jwt.util.ResponseMessage;
import org.jeecgframework.jwt.util.Result;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Title: Controller
 * @Description: POSTORDER
 * @author onlineGenerator
 * @date 2018-11-15 11:32:57
 * @version V1.0
 *
 */
@Api(value = "Postorder", description = "POSTORDER", tags = "postorderController")
@Controller
@RequestMapping("/postorderController")
public class PostorderController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(PostorderController.class);

    @Autowired
    private PostorderServiceI postorderService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private Validator validator;
    @Autowired
    private PopupDataBindUtil bindUtil;
    @Autowired
    private SysOrderVerifyServiceI sysOrderVerifyService;
    @Autowired
    private SysAppMessagesenderServiceI sysAppMessagesenderService;
    @Autowired
    private TraderServiceI traderService;
    @Autowired
    private SysAppRegionServiceI sysAppRegionService;
    @Autowired
    private VEcpPostorderServiceI vecpPostorderService;
    @Autowired
    private BzjOperatorServiceI bzjOperatorServiceI;

    /**
     * POSTORDER列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "list")
    public ModelAndView list(HttpServletRequest request, @RequestParam(required = false) String type) {
        request.setAttribute("type", type);
        return new ModelAndView("com/jeecg/demo/postorderList");

    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     * @throws Exception
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(PostorderEntity postorder, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, String type) throws Exception {
        CriteriaQuery cq = new CriteriaQuery(PostorderEntity.class, dataGrid);
        // 查询条件组装器
        // 如果绑定报表数据，则更新排序格式，将新增的虚拟列改为原表中对应列
        dataGrid.setSort(dataGrid.getSort().replace("commodityname", "commodityid"));
        StringBuffer stringBuffer = new StringBuffer();

        Map<String, String[]> parameterMap = request.getParameterMap();
        String beginTime = "";
        String endTime = "";
        for(Map.Entry<String, String[]> entry : parameterMap.entrySet()){
            if(entry.getKey().equals("potime_begin")){
                beginTime = entry.getValue()[0];
            }
            if(entry.getKey().equals("potime_end")){
                endTime = entry.getValue()[0];
            }
        }
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, postorder, request.getParameterMap());

        try {
            // 自定义追加查询条件
            // 挂牌
            if ("verifygp".equals(type)) {
                cq.eq("postatus", "2");
                cq.eq("isvalid", "1");
                cq.eq("trademodeid", 1);
                stringBuffer.append(" and trademodeid = '1'");
                stringBuffer.append(" and postatus = '2'");
                stringBuffer.append(" and isvalid = '1'");
                cq.add();
            }
            else if ("infogp".equals(type)) {
                cq.eq("trademodeid", 1);
                stringBuffer.append(" and trademodeid = '1'");
                cq.add();
            }
            // 招标
            else if ("verifyzb".equals(type)) {
                cq.eq("postatus", "2");
                cq.eq("isvalid", "1");
                cq.eq("trademodeid", 2);
                stringBuffer.append(" and trademodeid = '2'");
                stringBuffer.append(" and postatus = '2'");
                stringBuffer.append(" and isvalid = '1'");
                cq.add();
            }
            else if ("infozb".equals(type)) {
                cq.eq("trademodeid", 2);
                stringBuffer.append(" and trademodeid = '2'");
                cq.add();
            }
            // 拍卖
            else if ("verifypm".equals(type)) {
                cq.eq("postatus", "2");
                cq.eq("trademodeid", 3);
                cq.eq("isvalid", "1");
                request.setAttribute("pmys", "1");
                stringBuffer.append(" and trademodeid = '3'");
                stringBuffer.append(" and postatus = '2'");
                stringBuffer.append(" and isvalid = '1'");
                cq.add();
            }
            else if ("infopm".equals(type)) {
                cq.eq("trademodeid", 3);
                stringBuffer.append(" and trademodeid = '3'");
                cq.add();
            }
            // 团购
            else if ("verifytg".equals(type)) {
                cq.eq("postatus", "2");
                cq.eq("isvalid", "1");
                cq.eq("trademodeid", 4);
                stringBuffer.append(" and trademodeid = '4'");
                stringBuffer.append(" and postatus = '2'");
                stringBuffer.append(" and isvalid = '1'");
                cq.add();
            }
            else if ("infotg".equals(type)) {
                cq.eq("trademodeid", 4);
                stringBuffer.append(" and trademodeid = '4'");
                cq.add();
            }

        }
        catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        GetUserTenantId getuserfun = new GetUserTenantId();
        cq.add();
        this.postorderService.getDataGridReturn(cq, true);

        //挂单列表增加数量合计，金额合计功能
        if(postorder.getPocode() != null && !postorder.getPocode().equals("")){
            stringBuffer.append(" and POCODE = '"+postorder.getPocode()+"'");
        }

        if(postorder.getPotradername() != null && !postorder.getPotradername().equals("")){
            stringBuffer.append(" and POTRADERNAME like '%"+postorder.getPotradername()+"%'");
        }

        if(postorder.getDirection() != null && !postorder.getDirection().equals("")){
            stringBuffer.append(" and DIRECTION = '"+postorder.getDirection()+"'");
        }

        if(postorder.getIsvalid() != null && !postorder.getIsvalid().equals("")){
            stringBuffer.append(" and ISVALID = '"+postorder.getIsvalid()+"'");
        }

        if(!beginTime.equals("")){
            stringBuffer.append(" and to_char(potime,'yyyy-MM-dd') >= '"+beginTime+"'");
        }

        if(!endTime.equals("")){
            stringBuffer.append(" and to_char(potime,'yyyy-MM-dd') <= '"+endTime+"'");
        }

        String sql2 = stringBuffer.toString();
        //挂单总量
        String total = String.valueOf(this.postorderService.findOneForJdbc("select sum(poquantity) as ssum from POSTORDER where 1=1 "+ sql2, new Object[0]).get("ssum"));
        // 绑定非字典表数据
        bindUtil.BindDDName(dataGrid, "COMMODITY", "commodityname", "commodityid", "commodityid", "commodityname");

        dataGrid.setFooter("poprice: "+"数量合计（吨）:"+",poquantity: " + this.formatStr(total));

        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 删除POSTORDER
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(PostorderEntity postorder, HttpServletRequest request) {
        java.lang.String message = null;
        AjaxJson j = new AjaxJson();
        postorder = systemService.getEntity(PostorderEntity.class, postorder.getId());
        message = "删除成功";
        try {
            postorderService.delete(postorder);
            systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除POSTORDER
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "删除成功";
        try {
            for (String id : ids.split(",")) {
                PostorderEntity postorder = systemService.getEntity(PostorderEntity.class, Integer.parseInt(id));
                postorderService.delete(postorder);
                systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 添加POSTORDER
     *
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(PostorderEntity postorder, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "添加成功";
        try {
            postorderService.save(postorder);
            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "添加失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 更新POSTORDER
     *
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(PostorderEntity postorder, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "设置成功";
        PostorderEntity t = postorderService.get(PostorderEntity.class, postorder.getId());
        try {
            t.setIsvalid("0");
            MyBeanUtils.copyBeanNotNull2Bean(postorder, t);
            postorderService.saveOrUpdate(t);
            // 设置关联公告为无效
            String sql = "update ANNOUNCEMENT set zhuangt=-1 where poid='"
                    + postorder.getId() + "'";
            systemService.updateBySqlString(sql);
            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "设置失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * POSTORDER新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(PostorderEntity postorder, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(postorder.getId())) {
            postorder = postorderService.getEntity(PostorderEntity.class, postorder.getId());
            req.setAttribute("postorderPage", postorder);
        }
        return new ModelAndView("com/jeecg/demo/postorder-add");
    }

    /**
     * POSTORDER审核页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goVerify")
    public ModelAndView goVerify(PostorderEntity postorder, HttpServletRequest req, String type) {
        String imageServerUrl = ResourceUtil.getConfigByName("imageServerUrl");
        if (StringUtil.isNotEmpty(postorder.getId())) {
            postorder = postorderService.getEntity(PostorderEntity.class, postorder.getId());
            List<TraderEntity> list = traderService.findHql("from TraderEntity where traderid = ?", postorder.getPotraderid());
            TraderEntity trader = list.size() > 0 ? list.get(0) : null;

            List<SysAppRegionEntity> list2 = sysAppRegionService.findHql("from SysAppRegionEntity where regioncode = ? ", postorder.getDelivercity());

            SysAppRegionEntity region = list2.size() > 0 ? list2.get(0) : null;
            req.setAttribute("action", "postorderController.do?doVerify&type="
                    + type);

            List<Commodity> list3 = sysAppRegionService.findHql(
                    "from Commodity where commodityid = ? ", postorder.getCommodityid());
            Commodity commodity = list3.size() > 0 ? list3.get(0) : null;

            List<SysAppRegionEntity> list4 = sysAppRegionService.findHql(
                    "from SysAppRegionEntity where regioncode = ? ", commodity.getChdregioncode());
            SysAppRegionEntity regionChd = list4.size() > 0 ? list4.get(0) : null;

            List<VEcpPostorderEntity> list5 = vecpPostorderService.findHql(
                    "from VEcpPostorderEntity where poid = ?", postorder.getPoid());
            VEcpPostorderEntity vcepPostorder = list5.size() > 0 ? list5.get(0) : null;

            postorder.setSubtrademodeid(postorder.getSubtrademodeid().substring(2));
            if (postorder.getSubtrademodeid().equals("2")) {
                postorder.setCountdown2(postorder.getCountdown2()/60000);
            }else {
                postorder.setCountdown2(1);
            }

            req.setAttribute("postorderPage", postorder);
            req.setAttribute("trader", trader);
            req.setAttribute("region", region);

            req.setAttribute("commodity", commodity);
            req.setAttribute("chdregion", regionChd);
            req.setAttribute("vecppostorder", vcepPostorder);

            req.setAttribute("imageServerUrl", imageServerUrl);

        }
        return new ModelAndView("com/jeecg/demo/postorder-update");
    }

    /**
     * x 审核POSTORDER
     *
     * @return
     */
    @RequestMapping(params = "doVerify")
    @ResponseBody
    public AjaxJson doVerify(PostorderEntity postorder, HttpServletRequest request, String verifyflag, String verifynote, String pmygContent, String type, String termxml, String announTitle) {
        String message = null;
        String msg = null;
        AjaxJson j = new AjaxJson();
        /*
         * String pmygcontent = request.getParameter("pmygContent") == null ? ""
         * : request.getParameter("pmygContent").toString();
         */
        PostorderEntity t = postorderService.get(PostorderEntity.class,
                postorder.getId());
        TSUser u = ResourceUtil.getSessionUser();
        String beforestatus = "";
        try {
            // 根据认证申请状态判断审核前状态
            if (t.getPostatus().equals("1") || t.getPostatus().equals("2")) {
                beforestatus = "1";
            }
            else if (t.getPostatus().equals("3")) {
                beforestatus = "2";
            }
            else if (t.getPostatus().equals("4")) {
                beforestatus = "3";
            }

            // 设置审核记录
            SysOrderVerifyEntity verify = new SysOrderVerifyEntity();
            verify.setOrdid(postorder.getId());

            verify.setBeforestatus(beforestatus);
            verify.setVerifyuserid(0);
            verify.setVerifynote(verifynote);
            verify.setVerifytime(new Date());
            verify.setOrderid(1);
            // 设置系统消息
            SysAppMessagesenderEntity appmessage = new SysAppMessagesenderEntity();
            appmessage.setSender(0);
            appmessage.setReceiver(t.getPouserid());
            appmessage.setOrderid(1);
            appmessage.setMsgstatus("1");
            appmessage.setIsvalid("1");
            appmessage.setAppid("1");
            appmessage.setSendtime(new Date());
            appmessage.setFixedtime(new Date());

            if (type.equals("verifygp")) {
                verify.setOrdtype("POSTORDER_GP");
                msg = "您的挂牌报单" + t.getPocode() + "已审核通过,您可到挂牌列表中查看。";
                appmessage.setMsgtitle(msg);
                appmessage.setMsgcontent(msg);

            }
            else if (type.equals("verifyzb")) {
                verify.setOrdtype("POSTORDER_ZB");
                msg = "您的竞买报单" + t.getPocode() + "已审核通过,您可到竞买列表中查看。";
                appmessage.setMsgtitle(msg);
                appmessage.setMsgcontent(msg);
                t.setZbjgContent(pmygContent);
                t.setAnnounTitle(announTitle);
                String subtrademodeid = postorder.getSubtrademodeid();
                if (StringUtils.isNotEmpty(subtrademodeid)) {
                    t.setSubtrademodeid("PM" + subtrademodeid);
                    if ("2".equals(subtrademodeid)) {
                        Integer countdown2 = postorder.getCountdown2();
                        if (null != countdown2 && countdown2 > 0) {
                            countdown2 *= 60000;
                            t.setCountdown2(countdown2);
                        }
                    }else{
                        t.setCountdown2(null);
                    }
                }

            }
            else if (type.equals("verifypm")) {
                verify.setOrdtype("POSTORDER_PM");
                msg = "您的竞卖报单" + t.getPocode() + "已审核通过,您可到竞卖列表中查看。";
                appmessage.setMsgtitle(msg);
                appmessage.setMsgcontent(msg);
                t.setPmygContent(pmygContent);
                t.setAnnounTitle(announTitle);

                String subtrademodeid = postorder.getSubtrademodeid();
                if (StringUtils.isNotEmpty(subtrademodeid)) {
                    t.setSubtrademodeid("PM" + subtrademodeid);
                    if ("2".equals(subtrademodeid)) {
                        Integer countdown2 = postorder.getCountdown2();
                        if (null != countdown2 && countdown2 > 0) {
                            countdown2 *= 60000;
                            t.setCountdown2(countdown2);
                        }
                    }else{
                        t.setCountdown2(null);
                    }
                }

            }
            else if (type.equals("verifytg")) {
                verify.setOrdtype("POSTORDER_TG");
                msg = "您的团购报单" + t.getPocode() + "已审核通过,您可到挂牌列表中查看。";
                appmessage.setMsgtitle(msg);
                appmessage.setMsgcontent(msg);

            }

            if ("true".equals(verifyflag)) {
                message = "审核成功";

                if (null != verifynote && !verifynote.equals("")) {
                    message += "\r\n审核意见:" + verifynote;
                }

                // 保存审核记录
                verify.setVerifystatus("2");
                sysOrderVerifyService.save(verify);
                sysAppMessagesenderService.save(appmessage);
                // 保存状态
                t.setPostatus("3");
                // 修改交易有效期 竞价时间
                if (type.equals("verifygp")) {

                    t.setValidstartdate(postorder.getValidstartdate());
                    t.setValidenddate(postorder.getValidenddate());
                    t.setBidstarttime(postorder.getValidstartdate());
                    t.setBidendtime(postorder.getValidenddate());
                    t.setBidhalftime(postorder.getValidenddate());
                }
                else if (type.equals("verifyzb")) {
                    t.setValidstartdate(postorder.getBidstarttime());
                    t.setValidenddate(postorder.getBidendtime());
                    t.setBidstarttime(postorder.getBidstarttime());
                    t.setBidendtime(postorder.getBidendtime());
                    t.setBidhalftime(postorder.getBidendtime());

                }
                else if (type.equals("verifypm")) {
                    t.setValidstartdate(postorder.getBidstarttime());
                    t.setValidenddate(postorder.getBidendtime());
                    t.setBidstarttime(postorder.getBidstarttime());
                    t.setBidendtime(postorder.getBidendtime());
                    t.setBidhalftime(postorder.getBidendtime());

                }

                //新增于2024-07-10
                t.setVerifynote(verifynote);

                //新增于2024-05-24
                String res = "";
                boolean bool = bzjOperatorServiceI.isExistBzjData(t.getPocode(),String.valueOf(t.getPotraderid()),"0","0");
                if (!bool) {
                    res = bzjOperatorServiceI.operatorForPostorderByConfig(t);
                }
                if (res.equals("")) {
                    postorderService.saveOrUpdate(t);
                }else {
                    if (res.equals("success")) {
                        postorderService.saveOrUpdate(t);
                    }else {
                        t.setPostatus("2");
                        postorderService.saveOrUpdate(t);
                        message = "审核失败!原因：" + res;
                    }
                }
                systemService.addLog(message, Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);

            }
            else if ("false".equals(verifyflag)) {
                message = "审核退回";

                if (null != verifynote && !verifynote.equals("")) {
                    message += "\r\n退回原因:" + verifynote;
                }
                if (type.equals("verifygp")) {
                    msg = "抱歉，您的挂牌报单" + t.getPocode() + "审核未通过，您可以修改后重新提交。";
                    appmessage.setMsgtitle(msg);
                    appmessage.setMsgcontent(msg);

                }
                else if (type.equals("verifyzb")) {
                    msg = "抱歉，您的竞买报单" + t.getPocode() + "审核未通过，您可以修改后重新提交。";
                    appmessage.setMsgtitle(msg);
                    appmessage.setMsgcontent(msg);

                }
                else if (type.equals("verifypm")) {
                    msg = "抱歉，您的竞卖报单" + t.getPocode() + "审核未通过，您可以修改后重新提交。";
                    appmessage.setMsgtitle(msg);
                    appmessage.setMsgcontent(msg);

                }
                else if (type.equals("verifytg")) {
                    msg = "抱歉，您的团购报单" + t.getPocode() + "审核未通过，您可以修改后重新提交。";
                    appmessage.setMsgtitle(msg);
                    appmessage.setMsgcontent(msg);

                }

                // 保存审核记录
                verify.setVerifystatus("3");
                sysOrderVerifyService.save(verify);
                sysAppMessagesenderService.save(appmessage);
                // 保存状态
                t.setPostatus("7");
                postorderService.saveOrUpdate(t);

                systemService.addLog(message, Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);
            }

        }
        catch (Exception e) {
            e.printStackTrace();
            message = "审核失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * POSTORDER编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(PostorderEntity postorder,
            HttpServletRequest req) {
        if (StringUtil.isNotEmpty(postorder.getId())) {
            postorder = postorderService.getEntity(PostorderEntity.class, postorder.getId());

            TraderEntity trader = null;
            List<TraderEntity> list5 = traderService.findHql(
                    "from TraderEntity where traderid = ?", postorder.getPotraderid());
            if (list5.size() > 0) {
                trader = list5.get(0);
            }

            SysAppRegionEntity region = null;
            List<SysAppRegionEntity> list4 = sysAppRegionService.findHql(
                    "from SysAppRegionEntity where regioncode = ? ", postorder.getDelivercity());
            if (list4.size() > 0) {
                region = list4.get(0);
            }

            Commodity commodity = null;
            SysAppRegionEntity regionChd = null;
            List<Commodity> list = sysAppRegionService.findHql(
                    "from Commodity where commodityid = ? ", postorder.getCommodityid());
            if (list.size() > 0) {
                commodity = list.get(0);
                List<SysAppRegionEntity> list2 = sysAppRegionService.findHql(
                        "from SysAppRegionEntity where regioncode = ? ", commodity.getChdregioncode());
                if (list2.size() > 0) {
                    regionChd = list2.get(0);
                }
            }

            VEcpPostorderEntity vcepPostorder = null;
            List<VEcpPostorderEntity> list3 = vecpPostorderService.findHql(
                    "from VEcpPostorderEntity where poid = ?", postorder.getPoid());
            if (list3.size() > 0) {
                vcepPostorder = list3.get(0);
            }

            postorder.setSubtrademodeid(postorder.getSubtrademodeid().substring(2));
            if (postorder.getSubtrademodeid().equals("2")) {
                postorder.setCountdown2(postorder.getCountdown2()/60000);
            }else {
                postorder.setCountdown2(1);
            }

            String imageServerUrl = ResourceUtil.getConfigByName("imageServerUrl");

            req.setAttribute("action", "postorderController.do?doUpdate");
            req.setAttribute("postorderPage", postorder);
            req.setAttribute("trader", trader);
            req.setAttribute("region", region);
            req.setAttribute("commodity", commodity);
            req.setAttribute("chdregion", regionChd);
            req.setAttribute("vecppostorder", vcepPostorder);
            req.setAttribute("imageServerUrl", imageServerUrl);
            req.setAttribute("flags", req.getParameter("type"));
        }
        return new ModelAndView("com/jeecg/demo/postorder-update");
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        req.setAttribute("controller_name", "postorderController");
        return new ModelAndView("common/upload/pub_excel_upload");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public String exportXls(PostorderEntity postorder, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap, String ids) {
        CriteriaQuery cq = new CriteriaQuery(PostorderEntity.class, dataGrid);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, postorder, request.getParameterMap());
        cq.in("id", bindUtil.idsToIntegerArray(ids));
        cq.add();
        List<PostorderEntity> postorders = this.postorderService.getListByCriteriaQuery(cq, false);
        modelMap.put(NormalExcelConstants.FILE_NAME, "POSTORDER");
        modelMap.put(NormalExcelConstants.CLASS, PostorderEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("POSTORDER列表", "导出人:"
                        + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, postorders);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(PostorderEntity postorder, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(NormalExcelConstants.FILE_NAME, "POSTORDER");
        modelMap.put(NormalExcelConstants.CLASS, PostorderEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("POSTORDER列表", "导出人:"
                        + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, new ArrayList());
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<PostorderEntity> listPostorderEntitys = ExcelImportUtil.importExcel(file.getInputStream(), PostorderEntity.class, params);
                for (PostorderEntity postorder : listPostorderEntitys) {
                    postorderService.save(postorder);
                }
                j.setMsg("文件导入成功！");
            }
            catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(e.getMessage());
            }
            finally {
                try {
                    file.getInputStream().close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }

    @RequestMapping(value = "/list/{pageNo}/{pageSize}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "POSTORDER列表信息", produces = "application/json", httpMethod = "GET")
    public ResponseMessage<List<PostorderEntity>> list(
            @PathVariable("pageNo") int pageNo,
            @PathVariable("pageSize") int pageSize, HttpServletRequest request) {
        if (pageSize > Globals.MAX_PAGESIZE) {
            return Result.error("每页请求不能超过" + Globals.MAX_PAGESIZE + "条");
        }
        CriteriaQuery query = new CriteriaQuery(PostorderEntity.class);
        query.setCurPage(pageNo <= 0 ? 1 : pageNo);
        query.setPageSize(pageSize < 1 ? 1 : pageSize);
        List<PostorderEntity> listPostorders = this.postorderService
                .getListByCriteriaQuery(query, true);
        return Result.success(listPostorders);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据ID获取POSTORDER信息", notes = "根据ID获取POSTORDER信息", httpMethod = "GET", produces = "application/json")
    public ResponseMessage<?> get(
            @ApiParam(required = true, name = "id", value = "ID") @PathVariable("id") String id) {
        PostorderEntity task = postorderService.get(PostorderEntity.class, id);
        if (task == null) {
            return Result.error("根据ID获取POSTORDER信息为空");
        }
        return Result.success(task);
    }

    @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @ApiOperation(value = "创建POSTORDER")
    public ResponseMessage<?> create(
            @ApiParam(name = "POSTORDER对象") @RequestBody PostorderEntity postorder,
            UriComponentsBuilder uriBuilder) {
        Set<ConstraintViolation<PostorderEntity>> failures = validator
                .validate(postorder);
        if (!failures.isEmpty()) {
            return Result.error(JSONArray.toJSONString(BeanValidators
                    .extractPropertyAndMessage(failures)));
        }

        // 保存
        try {
            postorderService.save(postorder);
        }
        catch (Exception e) {
            e.printStackTrace();
            return Result.error("信息保存失败");
        }
        return Result.success(postorder);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @ApiOperation(value = "更新POSTORDER", notes = "更新POSTORDER")
    public ResponseMessage<?> update(
            @ApiParam(name = "POSTORDER对象") @RequestBody PostorderEntity postorder) {
        // 调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
        Set<ConstraintViolation<PostorderEntity>> failures = validator
                .validate(postorder);
        if (!failures.isEmpty()) {
            return Result.error(JSONArray.toJSONString(BeanValidators
                    .extractPropertyAndMessage(failures)));
        }

        // 保存
        try {
            postorderService.saveOrUpdate(postorder);
        }
        catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新信息失败");
        }

        // 按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
        return Result.success("更新信息成功");
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ResponseStatus(HttpStatus.NO_CONTENT)
    @ApiOperation(value = "删除POSTORDER")
    public ResponseMessage<?> delete(
            @ApiParam(name = "id", value = "ID", required = true) @PathVariable("id") String id) {
        logger.info("delete[{}]", id);
        // 验证
        if (StringUtils.isEmpty(id)) {
            return Result.error("ID不能为空");
        }
        try {
            postorderService.deleteEntityById(PostorderEntity.class, id);
        }
        catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败");
        }

        return Result.success();
    }

    public Date StringToDate(String datestr) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        Date dateTime = null;
        try {
            dateTime = simpleDateFormat.parse(datestr);
        }
        catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return dateTime;

    }

    private String formatStr(String str){
        String result = "";
        if (str == "null") {
            result = "0.0";
        }else {
            result = str;
        }
        return result;
    }
}
